package service

import (
	"encoding/json"
	"strings"
	"time"

	"net/http"

	"github.com/labstack/echo"
	"github.com/uber-go/zap"
)

type TempApp struct {
	Name          string `json:"name"`
	Group         string `json:"group"`
	Ip            string
	Host          string
	IsStarted     bool      `json:"is"`
	RestartTimes  int       `json:"rt"`
	LastStartTime time.Time `json:"lst"`
	LastErrorLog  string    `json:"lel"`

	RelVer  string `json:"rv"`
	ConfVer string `json:"cv"`
}

var AppMap = make(map[string]*App)

type App struct {
	IpToApp map[string]*TempApp
}

func queryVersions(c echo.Context) error {
	appS := c.FormValue("apps")
	configS := c.FormValue("configs")

	appMap := c.FormValue("appmap")

	host := c.FormValue("host")
	ip := c.FormValue("ip")

	var TempAppMap = make(map[string]*TempApp)
	err := json.Unmarshal([]byte(appMap), &TempAppMap)
	if err != nil {
		Logger.Warn("decode json err", zap.Error(err), zap.String("appmap", appMap))
		return err
	}

	// 保存上报的client状态
	for n, a := range TempAppMap {
		lock.RLock()
		app, ok := AppMap[n]
		lock.RUnlock()

		if !ok {
			ita := make(map[string]*TempApp)
			a.Ip = ip
			a.Host = host
			ita[ip] = a
			lock.Lock()
			AppMap[n] = &App{
				IpToApp: ita,
			}
			lock.Unlock()
		} else {
			a.Ip = ip
			a.Host = host
			lock.Lock()
			app.IpToApp[ip] = a
			lock.Unlock()
		}
	}

	// lock.RLock()
	// for k, app := range AppMap {
	// 	for k1, v1 := range app.IpToApp {
	// 		if v1.Host == "mt-uuidServer-1" {
	// 			fmt.Println(k, k1, v1)
	// 		}

	// 	}

	// }
	// lock.RUnlock()

	appSlice := strings.Split(appS, ",")
	configSlice := strings.Split(configS, ",")

	relRet := make(map[string]string)
	for _, app := range appSlice {
		lock.RLock()
		relVer := releaseVer[app]
		lock.RUnlock()

		relRet[app] = relVer
	}

	confRet := make(map[string]string)
	for _, conf := range configSlice {
		lock.RLock()
		confVer := configVer[conf]
		lock.RUnlock()

		confRet[conf] = confVer

	}

	return c.JSON(http.StatusOK, echo.Map{
		"release": relRet,
		"config":  confRet,
	})
}
